package buru.server.netty.rest;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * HttpServer class responsible for starting Netty.
 *
 * This should be made with a Builder-pattern-thingy in the near future. For now only a main-method.
 */
public class HttpServer {

    public static void main(String[] args)throws Exception {
        HttpServer h=new HttpServer( );
        h.start(9527);
    }

    private HttpServer( ) {

    }

    public void start(final int port) throws Exception {

        try (AutoNioEventLoopGroup bossGroup = new AutoNioEventLoopGroup();
             AutoNioEventLoopGroup workerGroup = new AutoNioEventLoopGroup()) {

            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new HttpServerPipelineFactory(HelloResource.class,HelloResource2.class))
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            Channel channel = bootstrap.bind(port).sync().channel();

//            Logs.log("service started on port {}", port);

            channel.closeFuture().sync();
        }
    }



    class AutoNioEventLoopGroup extends NioEventLoopGroup implements AutoCloseable {

        public AutoNioEventLoopGroup() {
            super(Runtime.getRuntime().availableProcessors());
        }

        @Override
        public void close() throws Exception {
            shutdownGracefully();
        }
    }



//    public static void main(String[] args) {
//        System.out.println("Starting the server...");
//
////        ChannelFactory factory = new NioServerSocketChannelFactory(
////                Executors.newCachedThreadPool(),
////                Executors.newCachedThreadPool());
//
//        ServerBootstrap server = new ServerBootstrap( );
//
//        server.
//
//        server.setPipelineFactory(new HttpServerPipelineFactory(HelloResource.class));
//
//        server.bind(new InetSocketAddress(8080));
//    }
}
